<template>
  <BasicModal ref="basicModal" v-bind="$attrs" @register="registerModal" destroyOnClose width="60%" :title="title" @ok="handleSubmit">
    <BasicForm ref="basicForm" @register="registerForm" />
  </BasicModal>
</template>

<script lang="ts" setup>
  import { ref, computed, unref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { formSchema } from '../AssetInfo.data';
  import { saveOrUpdate } from '../AssetInfo.api';
  import dayjs from 'dayjs';
  import { useI18n } from '/@/hooks/web/useI18n';
  const { t, isCN } = useI18n('common');
  // Emits声明
  const emit = defineEmits(['register', 'success']);
  const isUpdate = ref(true);
  //表单配置
  const [registerForm, { setProps, resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: isCN ? 100 : 180,
    schemas: formSchema,
    showActionButtonGroup: false,
    baseColProps: { sm: 24, xl: 12 },
  });

  //表单赋值
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    //重置表单
    await resetFields();
    setModalProps({ confirmLoading: false, showCancelBtn: !!data?.showFooter, showOkBtn: !!data?.showFooter });
    isUpdate.value = !!data?.isUpdate;
    import.meta.env.DEV &&
      (await setFieldsValue({
        name: dayjs().format('HH:mm:ss') + '测试资产' + dayjs().format('MM-DD'),
        cartegory: '1705060380059308034',
        custodyDepartment: 'c6d7cb4deeac411cb3384b1b31278596',
        useState: '0',
        position: '1729767372975652866',
        price: Math.random() * 100 + 100,
      }));
    if (unref(isUpdate)) {
      //表单赋值
      await setFieldsValue({
        ...data.record,
      });
    }
    // 隐藏底部时禁用整个表单
    setProps({ disabled: !data?.showFooter });
  });
  //设置标题
  const title = computed(() => (!unref(isUpdate) ? t('addText') : t('editText')));
  //表单提交事件
  async function handleSubmit() {
    try {
      let values = await validate();
      setModalProps({ confirmLoading: true });
      //提交表单
      await saveOrUpdate(values, isUpdate.value);
      //关闭弹窗
      closeModal();
      //刷新列表
      emit('success');
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
  const basicForm = ref<InstanceType<typeof BasicForm>>();
  const basicModal = ref<InstanceType<typeof BasicModal>>();
  defineExpose({ basicForm, basicModal });
</script>

<style lang="less" scoped>
  /** 时间和数字输入框样式 */
  :deep(.ant-input-number) {
    width: 100%;
  }

  :deep(.ant-calendar-picker) {
    width: 100%;
  }
</style>
